import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class FileStream {
    static void copyFile(String resource, String target) throws IOException {
        try(InputStream inputStream = new FileInputStream(resource);
            OutputStream outputStream = new FileOutputStream(target)) {
            inputStream.transferTo(outputStream);
        }
    }

    static void readFile() throws IOException {
        try (InputStream input = new FileInputStream("src/Range.java")) {
            byte[] buffer = new byte[1000];
            int n;
            while ((n = input.read(buffer)) != -1) {
                System.out.println("read " + n + " bytes.");
            }
        }
    }

    static void getStringFromBytes() throws IOException {
        byte[] data = { 72, 101, 108, 108, 111, 33 };
        try (InputStream input = new ByteArrayInputStream(data)) {
            String s = FileStream.readAsString(input);
            System.out.println(s);
        }
    }

    public static String readAsString(InputStream input) throws IOException {
        int n;
        StringBuilder sb = new StringBuilder();
        while ((n = input.read()) != -1) {
            sb.append((char) n);
        }
        return sb.toString();
    }

    static void writeFile() throws IOException {
        Path path = Path.of("src/test.txt");
        String content1 = Files.readString(path, StandardCharsets.UTF_8);
        List<String> list = Files.readAllLines(path, StandardCharsets.UTF_8);
        List<String> listLines = List.of(new String[]{"test", "Hello", "新增内容"});
        Files.writeString(path, "新增内容", StandardCharsets.UTF_8);
        Files.write(path, listLines);
        System.out.println(list);
    }
}
